<template>
  <!-- 手动结算 -->
  <div>
    <base-modal
      title="添加服务商结算明细"
      :show.sync="Visible"
      width="700px"
      append-to-body
      @close="Close"
    >
      <div v-loading="loading">
        <form-builder
          class="task-form-builder"
          ref="form"
          :key="formBuilderKey"
          :fields="taskFormFields"
          :value="taskValue"
          mode="task"
          @update="update"
        >
          <!-- 工时服务费 -->
          <!-- <template slot="hourlyServiceFee" slot-scope="{ field, value }">
            <form-item :label="field.displayName" :validation="false">
              <div class="form-taskNo">
                <el-input
                  :disabled="disabledHourlyServiceFee"
                  @input="value => SetUpdate('hourlyServiceFee', value)"
                  @change="value => SetUpdate('hourlyServiceFee', value)"
                  v-model="taskValue.hourlyServiceFee"
                  type="number"
                />
              </div>
            </form-item>
          </template> -->
          <!-- 工时服务费 -->
          <!-- 里程费 -->
          <!-- <template slot="mileageFee" slot-scope="{ field, value }">
            <form-item :label="field.displayName" :validation="false">
              <div class="form-taskNo">
                <el-input
                  @input="value => SetUpdate('mileageFee', value)"
                  v-model="taskValue.mileageFee"
                  @change="value => SetUpdate('mileageFee', value)"
                  type="number"
                />
              </div>
            </form-item>
          </template> -->
          <!-- 里程费 -->
          <!-- 补贴费 -->
          <!-- <template slot="subsidyFee" slot-scope="{ field, value }">
            <form-item :label="field.displayName" :validation="false">
              <div class="form-taskNo">
                <el-input
                  :disabled="disabledSubsidyFee"
                  @input="value => SetUpdate('subsidyFee', value)"
                  v-model="taskValue.subsidyFee"
                  @change="value => SetUpdate('subsidyFee', value)"
                  type="number"
                />
              </div>
            </form-item>
          </template> -->
          <!-- 补贴费 -->
          <!-- 其他费用 -->
          <!-- <template slot="otherFee" slot-scope="{ field, value }">
            <form-item :label="field.displayName" :validation="false">
              <div class="form-taskNo">
                <el-input
                  @input="value => SetUpdate('otherFee', value)"
                  v-model="taskValue.otherFee"
                  @change="value => SetUpdate('otherFee', value)"
                  type="number"
                />
              </div>
            </form-item>
          </template> -->
          <!-- 其他费用 -->
          <!-- 总费用 -->
          <template slot="sumAmount" slot-scope="{ field, value }">
            <form-item :label="field.displayName" :validation="false">
              <div class="form-taskNo">
                <el-input :value="Sum" type="number" :disabled="true" />
              </div>
            </form-item>
          </template>
          <!-- 总费用 -->
        </form-builder>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="Close">取 消</el-button>
        <el-button :loading="SaveLoading" type="primary" @click="Save">
          保 存
        </el-button>
      </span>
    </base-modal>
  </div>
</template>

<script>
import { uuid } from 'pub-bbx-utils';
import * as TaskApi from '@src/api/TaskApi.ts';
import {
  MAX_InputNumber,
  MAX_InputNumber_Value,
  Min_InputNumber,
  Min_InputNumber_Value,
} from '@src/util/math.js';
export default {
  name: 'settlement',
  props: {
    isShow: {
      type: Boolean,
      default: false,
    },
    // 工单数据与权限
    shareData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    // 服務商數據
    SettlementData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      loading: false,
      TaskKey: 0,
      // 表单唯一值
      formBuilderKey: uuid(),
      // 表单初始数据
      taskValue: {
        // 工单id
        taskId: '',
        // 工单编号
        taskNo: '',
        // 备件
        attachment: [],
      },
      // 表单数据
      taskFormFields: [],
      SaveLoading: false,
      Visible: true,
      disabledHourlyServiceFee: true,
      disabledSubsidyFee: true,
      Sum: 0,
    };
  },

  mounted() {
    for (let index in this.taskFormFields) {
      if (this.taskFormFields[index].fieldName === 'attachment') {
        // 备件
        this.taskValue[this.taskFormFields[index].fieldName] = [];
      } else {
        this.taskValue[this.taskFormFields[index].fieldName] = '';
      }
    }

    this.GetbuildFields();
  },

  watch: {
    isShow: {
      immediate: true,
      deep: true,
      handler(newValue) {
        this.Visible = newValue;
      },
    },
    shareData: {
      immediate: true,
      deep: true,
      handler(newValue) {
        // 获取工单id、工单编号、服务商id
        let { id, taskNo } = newValue.task;
        this.taskValue.taskId = id;
        this.taskValue.taskNo = taskNo;
      },
    },
  },

  methods: {
    change() {
      this.$forceUpdate();
    },
    SetUpdate(key, value) {
      this.taskValue[key] = Number(value).toFixed(2);
      if (Number(value) > MAX_InputNumber) {
        this.taskValue[key] = MAX_InputNumber_Value;
      }
      if (Number(value) < Min_InputNumber) {
        this.taskValue[key] = Min_InputNumber_Value;
      }
      this.SetSum();
      this.$forceUpdate();
    },
    update({ field, newValue }) {
      this.taskValue[field.fieldName] = newValue;
      this.$forceUpdate();
      this.calculateFeeTotal(field.fieldName);
      this.SetSum();
    },
    SetSum() {
      let Num = 0;
      for (let index in this.taskFormFields) {
        if (
          this.taskFormFields[index].formType === 'number' &&
          this.taskFormFields[index].fieldName !== 'sumAmount' &&
          !this.taskFormFields[index].parentFieldName && // 没有parentFieldName的是明细合计
          this.taskValue[this.taskFormFields[index].fieldName]
        ) {
          Num += Number(this.taskValue[this.taskFormFields[index].fieldName]);
        }
      }
      this.Sum = Num?.toFixed(2);
      this.$set(this.taskValue, 'sumAmount', this.Sum);
    },
    calculateFeeTotal(fieldName) {
      const isHourlyServiceFeeChild = this.getFeeChild(fieldName, 'hourlyServiceFee');
      const isSubsidyFeeChild = this.getFeeChild(fieldName, 'subsidyFee');
      const isMileageFeeFeeChild = this.getFeeChild(fieldName, 'mileageFee');

      if(isHourlyServiceFeeChild) {
        this.setFeeTotal('hourlyServiceFee');
      }
      if(isSubsidyFeeChild) {
        this.setFeeTotal('subsidyFee');
      }
      if(isMileageFeeFeeChild) {
        this.setFeeTotal('mileageFee');
      }
    },
    getFeeChild(fieldName, feeType) {
      return fieldName.split('_') && fieldName.split('_').length > 1 && fieldName.split('_')[0] === feeType;
    },
    setFeeTotal(feeType) {
      const total = this.getFeeTotal(feeType);
      this.$set(this.taskValue, feeType, total);
    },
    getFeeTotal(feeType) {
      const feeMap = Object.keys(this.taskValue).filter(item => this.getFeeChild(item, feeType));
      return feeMap.reduce((acc, key) => {
        return acc + Number(this.taskValue[key]);
      }, 0);
    },
    isFeeDisabled(fieldSuffix) {
      return this.taskFormFields.some(item => fieldSuffix === item.parentFieldName); 
    },
    GetbuildFields() {
      this.loading = true;
      TaskApi.buildFields({taskId: this.taskValue.taskId}).then(res => {
        if (res.code === 0) {
          this.taskFormFields = res.result || [];
          this.taskFormFields.forEach(field => {
            // 费用合计禁止编辑
            const disabledKeys = ['hourlyServiceFee', 'subsidyFee'];
            disabledKeys.forEach(key => {
              if (field.fieldName === key && this.isFeeDisabled(key)) {
                field.disabled = true;
              }
            });
            field.isNull = 1;
          });

          // 无明细允许编辑总计
          this.disabledHourlyServiceFee = this.setDisabled('hourlyServiceFee');
          this.disabledSubsidyFee = this.setDisabled('subsidyFee');
          this.SetData();
          this.SetSum();
        }
      })
        .catch(error => {
          console.error(error);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    setDisabled(type) {
      const existChild = this.taskFormFields.some(item => type === item?.setting?.formType);
      if(existChild) return true;
      return false;
    },
    SetData() {
      for (let index in this.taskFormFields) {
        let value = this.SettlementData[this.taskFormFields[index].fieldName];
        if(this.taskFormFields[index].formType === 'number') {
          this.taskValue[this.taskFormFields[index].fieldName] = value || 0;
        }

        if (![null, undefined, '', 0].includes(value)) {
          this.taskValue[this.taskFormFields[index].fieldName] = value;
        }
      }
    },
    Close() {
      this.$emit('close');
    },
    buildParams() {
      const hourlyServiceFee = this.getFeeParams('hourlyServiceFee');
      const mileageFee = this.getFeeParams('mileageFee');
      const subsidyFee = this.getFeeParams('subsidyFee');
      this.taskValue.feeRecord = {
        hourlyServiceFee,
        mileageFee,
        subsidyFee
      }
    },
    getFeeParams(feeType) {
      const fees = {};
      for(const key in this.taskValue) {
        if(key.split('_') && key.split('_').length > 1 && key.split('_')[0] === feeType) {
          fees[key.split('_')[1]] = this.taskValue[key];
        }
      }
      return fees;
    },
    validateInput(value) {
      const valueStr = `${value}`;
      const decimalIndex = valueStr.indexOf('.');
      let integerPartLength = 0;
      let decimalPartLength = 0;

      if (decimalIndex !== -1) {
        integerPartLength = decimalIndex;
        decimalPartLength = valueStr.substring(decimalIndex + 1).length;
      } else {
        integerPartLength = valueStr.length;
      }

      if(integerPartLength > 8 || decimalPartLength > 2 || value < 0) return true
      return false;
    },
    async Save() {
      let validateRes = await this.$refs.form.validate();
      for(const index in this.taskFormFields) {
        const formType = this.taskFormFields[index].formType;
        const fieldName = this.taskFormFields[index].fieldName;
        const value = Number(this.taskValue[fieldName]);
        if(formType === 'number' && this.validateInput(value)) {
          return this.$message.warning(this.$t('common.base.tip.numericalVerificationTip'));
        }
      }

      this.buildParams();
      if (validateRes) {
        this.SaveLoading = true;
        TaskApi.taskProviderSettleApproveApply(this.taskValue).then(res => {
          this.SaveLoading = false;
          if (res.code === 0) {
            this.$message.success(this.$t('common.base.tip.addSuccess'));
            this.$emit('save');
            this.Close();
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
